import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/input_formatter/money_util.dart';
import 'package:objectbox/objectbox.dart';
import 'package:flutter_deer/dl/dl.dart';
import 'package:flutter_deer/generated/res_upload_oil_entity.dart';
import 'package:flutter_deer/objectbox.g.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/socket/bean/fcc_cmd.dart';
import 'package:flutter_deer/util/user_config_manager.dart';
import 'beans/shift/current_shift_entity.dart';
import 'beans/get_user_info_entity.dart';
import 'database_manager.dart';
import 'order_status.dart';

// 基础实体类（对应 Drift 的 MdcMaxTtcBean）
@Entity()
class MdcMaxTtcBean {
  @Id() // 自增主键
  int id = 0;

  @Unique(onConflict: ConflictStrategy.replace)
  int chl = 0;

  int mdcNo = 0;
  int maxTTC = 0;

  @override
  String toString() {
    return 'id:$id,chl:$chl,maxTTC:$maxTTC';
  }

  ///手动解析
  static MdcMaxTtcBean fromJson(dynamic json) {
    return MdcMaxTtcBean()
      ..maxTTC = json['fccTTC'] as int
      ..chl = json['chl'] as int;
  }

  Map<String, dynamic> toServerJsonMap() {
    return {
      'cmdType': FccCMD.GetMaxTTC,
      'chl': chl,
    };
  }

  ///删除全部
  static void deleteAll() {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<MdcMaxTtcBean>();
    box.removeAll();
    print('[deleteAll]--->MdcMaxTtcBean');
  }

  ///检测是否需要回叫并添加任务
  static void checkAndAddCallBack(AppOrderBean target) {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<MdcMaxTtcBean>();
    final boxCallBack = store.box<MdcCallBackBean>();
    // 构建查询构建器
    final queryBuilder = box.query(MdcMaxTtcBean_.mdcNo.equals(target.mdcNo) & MdcMaxTtcBean_.chl.equals(target.chl));
    // 构建查询
    final query = queryBuilder.build();
    try {
      // 执行查询并获取结果
      final results = query.find();
      // 提取所有 MdcMaxTtcBean 的 maxTTC
      final maxTTCs = results.map((bean) => bean.maxTTC).toList();
      // 计算最大的 maxTTC
      int maxMaxTTC = maxTTCs.isNotEmpty ? maxTTCs.reduce((a, b) => a > b ? a : b) : 0;
      // 如果maxTTC小于当前订单的fccTTC，更新本地maxTTC记录
      if (maxMaxTTC < target.fccTTC) {
        final bean = MdcMaxTtcBean()
          ..maxTTC = target.fccTTC
          ..chl = target.chl
          ..mdcNo = target.mdcNo;
        box.put(bean);
        print('[updateMaxTTC by order] [chl:${bean.chl}] [$maxMaxTTC] ---> [${bean.maxTTC}]');
      }
      // 如果maxTTC远远小于当前订单的fccTTC，最多回叫50笔数据
      if (maxMaxTTC > 0 && maxMaxTTC < target.fccTTC - 50) {
        maxMaxTTC = target.fccTTC - 50;
      }
      // 遍历 maxTTCs，插入回叫任务
      if (maxMaxTTC > 0) {
        for (int i = maxMaxTTC + 1; i < target.fccTTC; i++) {
          final bean = MdcCallBackBean()
            ..fccTTC = i
            ..chl = target.chl
            ..mdcNo = target.mdcNo;
          boxCallBack.put(bean);
          print('[insertCallBackTTC by order]             ---> $bean');
        }
      }
    } catch (e, s) {
      print('[updateMaxTTC by order---error] ${target.toStringOrder()} [error]: \n$e \n$s');
    } finally {
      // 关闭查询以释放资源
      query.close();
    }
  }

  ///检测是否需要回叫并添加任务
  static void checkAndAddCallBackByMax(int mdcNo, int chlNo, int serverMaxTTC) {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<MdcMaxTtcBean>();
    final boxCallBack = store.box<MdcCallBackBean>();
    // 构建查询构建器
    final queryBuilder = box.query(MdcMaxTtcBean_.mdcNo.equals(mdcNo) & MdcMaxTtcBean_.chl.equals(chlNo));
    // 构建查询
    final query = queryBuilder.build();
    try {
      // 执行查询并获取结果
      final results = query.find();
      // 提取所有 MdcMaxTtcBean 的 maxTTC
      final maxTTCs = results.map((bean) => bean.maxTTC).toList();
      // 计算最大的 maxTTC
      int maxMaxTTC = maxTTCs.isNotEmpty ? maxTTCs.reduce((a, b) => a > b ? a : b) : 0;
      // 如果maxTTC小于当前订单的fccTTC，更新本地maxTTC记录

      final bean = MdcMaxTtcBean()
        ..maxTTC = serverMaxTTC
        ..chl = chlNo
        ..mdcNo = mdcNo;
      box.put(bean);
      print('[updateMaxTTC by max] [chl:${bean.chl}] [$maxMaxTTC] ---> [${bean.maxTTC}]');

      // 如果maxTTC远远小于当前订单的fccTTC，最多回叫50笔数据
      if (maxMaxTTC > 0 && maxMaxTTC < serverMaxTTC - 50) {
        maxMaxTTC = serverMaxTTC - 50;
      }
      // 遍历 maxTTCs，插入回叫任务
      if (maxMaxTTC > 0) {
        for (int i = maxMaxTTC + 1; i < serverMaxTTC + 1; i++) {
          final bean = MdcCallBackBean()
            ..fccTTC = i
            ..chl = chlNo
            ..mdcNo = mdcNo;
          boxCallBack.put(bean);
          print('[insertCallBackTTC] by max             --->$bean');
        }
      }
    } catch (e, s) {
      print('[updateMaxTTC by max---error] [error]: \n$e \n$s');
    } finally {
      // 关闭查询以释放资源
      query.close();
    }
  }
}

// 回调扩展实体（继承 MdcMaxTtcBean）
@Entity()
class MdcCallBackBean {
  @Id() // 自增主键
  int id = 0;

  int chl = 0;
  int mdcNo = 0;
  int fccTTC = 0;

  int retryCount = 0;

  // 唯一约束
  @Unique(onConflict: ConflictStrategy.fail)
  String get uniqueKey => '$chl-$fccTTC';

  @override
  String toString() {
    return 'id:$id,chl:$chl,fccTTC:$fccTTC,uniqueKey:$uniqueKey';
  }

  Map<String, dynamic> toServerJsonMap() {
    return {
      'cmdType': FccCMD.QryTTC,
      'chl': chl,
      'fccTTC': fccTTC,
    };
  }

  ///删除全部
  static void deleteAll() {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<MdcCallBackBean>();
    box.removeAll();
    print('[deleteAll]--->MdcCallBackBean');
  }

  ///手动解析
  static MdcCallBackBean fromJson(dynamic json) {
    return MdcCallBackBean()
      ..fccTTC = json['fccTTC'] as int
      ..chl = json['chl'] as int;
  }

  ///查询回叫记录
  static List<MdcCallBackBean> queryCallBackBean(AppOrderBean target) {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<MdcCallBackBean>();
    // 构建查询构建器
    final queryBuilder = box.query(MdcCallBackBean_.fccTTC.equals(target.fccTTC) & MdcCallBackBean_.mdcNo.equals(target.mdcNo) & MdcCallBackBean_.chl.equals(target.chl));
    // 构建查询
    final query = queryBuilder.build();
    // 执行查询并获取结果
    final results = query.find();
    // 关闭查询以释放资源
    query.close();
    return results;
  }

  ///查询回叫记录Chl
  static List<MdcCallBackBean> queryCallBackBeanByChl(int mdcNo, int chl) {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<MdcCallBackBean>();
    // 构建查询构建器
    final queryBuilder = box.query(MdcCallBackBean_.mdcNo.equals(mdcNo) & MdcCallBackBean_.chl.equals(chl));
    // 构建查询
    final query = queryBuilder.build();
    // 执行查询并获取结果
    final results = query.find();
    // 关闭查询以释放资源
    query.close();
    return results;
  }

  ///删除回叫任务
  static void deleteCallBackBean(AppOrderBean target) {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<MdcCallBackBean>();
    // 构建查询构建器
    final queryBuilder = box.query(MdcCallBackBean_.fccTTC.equals(target.fccTTC) & MdcCallBackBean_.mdcNo.equals(target.mdcNo) & MdcCallBackBean_.chl.equals(target.chl));
    // 构建查询
    final query = queryBuilder.build();
    try {
      // 执行查询并获取结果
      final results = query.find();
      // 提取所有 MdcCallBackBean 的 id
      final idsToRemove = results.map((bean) => bean.id).toList();
      // 批量删除
      box.removeMany(idsToRemove);
    } finally {
      // 关闭查询以释放资源
      query.close();
    }
  }
}

//订单实体（继承 AppOilGunBean）
@immutable
@Entity()
class AppOrderBean {
  @Id() // 自增主键
  int id = 0;

  int chl = 0;
  int mdcNo = 0;
  int fccTTC = 0;

  int retryCount = 0;

  int nzl = 0; // IntColumn
  int gas = 0; // IntColumn
  int prc = 0; // IntColumn
  int sta = 1; // IntColumn
  int mny = 0; // IntColumn

  int vol = 0; // Column<int>()
  int vtot0 = 0; // Column<int>()
  int vtot1 = 0; // Column<int>()

  int cardType = 0; // IntColumn
  String cardNo = ''; // TextColumn

  int reply = 0; // IntColumn

  String orderTime = ''; // TextColumn
  String time0 = ''; // TextColumn (抬枪时间)
  String time1 = ''; // TextColumn (挂枪时间)
  int mdcOrderTime = 0; // Column<int>()

  @Unique(onConflict: ConflictStrategy.fail)
  String energyOrderCode = ''; // TextColumn

  /// -------------------

  String energyOrderId = ''; // TextColumn
  String mixPayOrderId = ''; // TextColumn

  String shiftNo = ''; // TextColumn
  String shiftId = ''; // TextColumn

  String suspendTime = ''; // TextColumn (挂起时间)

  bool isSynced = false; // BoolColumn

  String shelfId = ''; // TextColumn
  String unitName = ''; // TextColumn
  String mchGoodsId = ''; // TextColumn
  String categoryId = ''; // TextColumn
  String mchGoodsName = ''; // TextColumn (goodsShortName)
  String goodsSkuName = ''; // TextColumn
  String goodsPlatformPrice = ''; // TextColumn

  int exceptionType = 0; // IntColumn (异常类型（0：无异常: 1：价格异常）)

  int discardType = 0; // IntColumn (0-自定义 1-回罐 2-数据错误)
  String discardOperatorId = ''; // TextColumn (弃单操作员ID)
  String discardReason = ''; // TextColumn (弃单原因)
  int isAutoMath = 0; // IntColumn (0油机数据 1手动补录，2系统补录)

  //@OrderStatus()
  int energyOrderStatus = OrderOilStatus.WAIT_PAY; // IntColumn

  // 不入库
  // @Transient()
  // RxBool selected = false.obs; // BoolColumn

  // 上传油单需要的字段

  // 获取格式化后的价格
  String get formatPrice {
    final gunByNzl = UserConfigManager.getGunByNzl(nzl);
    return '${gunByNzl?.goodsSkuPrice?.formatYuan ?? ''}元/$unitName';
  }

  // 获取格式化后的金额
  String get formatMny {
    return mny.toYuan.replaceAll('.00', '');
  }

  // 获取实时的价格异常情况
  String get formatExceptionType {
    final gunByNzl = UserConfigManager.getGunByNzl(nzl);
    if (gunByNzl == null) {
      return '';
    }
    final int excType = (gunByNzl.getPriceFen() == prc || prc == 0) ? 0 : 1;
    if (excType == 1) {
      return '平台价(${formatPrice})';
    }
    return '';
  }

  ///手动解析 {"cmdType":101,"nzl":15,"sta":1,"vol":0,"mny":0}
  static void fromJsonState(AppOrderBean bean, dynamic json) {
    final _nzl = json['nzl'] as int? ?? 0;
    bean
      ..nzl = _nzl
      ..sta = json['sta'] as int? ?? 0
      ..mny = json['mny'] as int? ?? 0
      ..vol = json['vol'] as int? ?? 0;
  }

  String toStringState() {
    return 'nzl:$nzl,sta:$sta,mny:$mny,vol:$vol';
  }

  String toStringOrder() {
    return 'id:$id,nzl:$nzl,mny:$mny,vol:$vol,energyOrderCode:$energyOrderCode,energyOrderId:$energyOrderId,isSynced:$isSynced,mdcOrderTime:$mdcOrderTime,energyOrderStatus:$energyOrderStatus,shiftNo:$shiftNo';
  }

  String toStringTake() {
    return '${nzl.toString().padLeft(2, '0')}/${mchGoodsName} \t\t\t ${mny.toYuan}元/${vol.toYuan}L  \t\t\t  \t\t\t ';
  }

  /// 转换为 JSON 格式的 Map
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'chl': chl,
      'mdcNo': mdcNo,
      'fccTTC': fccTTC,
      'retryCount': retryCount,
      'nzl': nzl,
      'gas': gas,
      'prc': prc,
      'sta': sta,
      'mny': mny,
      'vol': vol,
      'vtot0': vtot0,
      'vtot1': vtot1,
      'cardType': cardType,
      'cardNo': cardNo,
      'reply': reply,
      'orderTime': orderTime,
      'time0': time0,
      'time1': time1,
      'mdcOrderTime': mdcOrderTime,
      'energyOrderCode': energyOrderCode,
      'energyOrderId': energyOrderId,
      'mixPayOrderId': mixPayOrderId,
      'shiftNo': shiftNo,
      'shiftId': shiftId,
      'suspendTime': suspendTime,
      'isSynced': isSynced,
      'shelfId': shelfId,
      'unitName': unitName,
      'mchGoodsId': mchGoodsId,
      'categoryId': categoryId,
      'mchGoodsName': mchGoodsName,
      'goodsSkuName': goodsSkuName,
      'goodsPlatformPrice': goodsPlatformPrice,
      'exceptionType': exceptionType,
      'discardType': discardType,
      'discardOperatorId': discardOperatorId,
      'discardReason': discardReason,
      'isAutoMath': isAutoMath,
      'energyOrderStatus': energyOrderStatus,
    };
  }

  // ... existing code ...
static AppOrderBean fromJson(Map<String, dynamic> json) {
    return AppOrderBean()
      ..id = json['id'] as int? ?? 0
      ..chl = json['chl'] as int? ?? 0
      ..mdcNo = json['mdcNo'] as int? ?? 0
      ..fccTTC = json['fccTTC'] as int? ?? 0
      ..retryCount = json['retryCount'] as int? ?? 0
      ..nzl = json['nzl'] as int? ?? 0
      ..gas = json['gas'] as int? ?? 0
      ..prc = json['prc'] as int? ?? 0
      ..sta = json['sta'] as int? ?? 0
      ..mny = json['mny'] as int? ?? 0
      ..vol = json['vol'] as int? ?? 0
      ..vtot0 = json['vtot0'] as int? ?? 0
      ..vtot1 = json['vtot1'] as int? ?? 0
      ..cardType = json['cardType'] as int? ?? 0
      ..cardNo = json['cardNo'] as String? ?? ''
      ..reply = json['reply'] as int? ?? 0
      ..orderTime = json['orderTime'] as String? ?? ''
      ..time0 = json['time0'] as String? ?? ''
      ..time1 = json['time1'] as String? ?? ''
      ..mdcOrderTime = json['mdcOrderTime'] as int? ?? 0
      ..energyOrderCode = json['energyOrderCode'] as String? ?? ''
      ..energyOrderId = json['energyOrderId'] as String? ?? ''
      ..mixPayOrderId = json['mixPayOrderId'] as String? ?? ''
      ..shiftNo = json['shiftNo'] as String? ?? ''
      ..shiftId = json['shiftId'] as String? ?? ''
      ..suspendTime = json['suspendTime'] as String? ?? ''
      ..isSynced = json['isSynced'] as bool? ?? false
      ..shelfId = json['shelfId'] as String? ?? ''
      ..unitName = json['unitName'] as String? ?? ''
      ..mchGoodsId = json['mchGoodsId'] as String? ?? ''
      ..categoryId = json['categoryId'] as String? ?? ''
      ..mchGoodsName = json['mchGoodsName'] as String? ?? ''
      ..goodsSkuName = json['goodsSkuName'] as String? ?? ''
      ..goodsPlatformPrice = json['goodsPlatformPrice'] as String? ?? ''
      ..exceptionType = json['exceptionType'] as int? ?? 0
      ..discardType = json['discardType'] as int? ?? 0
      ..discardOperatorId = json['discardOperatorId'] as String? ?? ''
      ..discardReason = json['discardReason'] as String? ?? ''
      ..isAutoMath = json['isAutoMath'] as int? ?? 0
      ..energyOrderStatus = json['energyOrderStatus'] as int? ?? OrderOilStatus.WAIT_PAY;
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    if (other is! AppOrderBean) return false;
    return other.energyOrderCode == energyOrderCode;
  }

  @override
  int get hashCode {
    return energyOrderCode.hashCode;
  }

  ///手动解析油单
  static AppOrderBean fromJsonOrder(dynamic json) {
    final time0 = (json['time0'] as String? ?? '').replaceAll('T', ' ');
    final time1 = (json['time1'] as String? ?? '').replaceAll('T', ' ');
    final nzl = json['nzl'] as int? ?? 0;
    final fccTTC = json['fccTTC'] as int? ?? 0;
    final a = AppOrderBean();
    final gunByNzl = UserConfigManager.getGunByNzl(nzl);
    final _prc = json['prc'] as int? ?? 0;
    final _prc2 = (_prc == 100) ? 0 : _prc;
    return a
      ..fccTTC = fccTTC
      ..chl = json['chl'] as int? ?? 0
      ..nzl = nzl
      ..gas = json['gas'] as int? ?? 0
      ..prc = _prc2
      ..sta = 1
      ..mny = json['mny'] as int? ?? 0
      ..vol = json['vol'] as int? ?? 0
      ..vtot0 = json['vtot0'] as int? ?? 0
      ..vtot1 = json['vtot1'] as int? ?? 0
      ..cardType = json['cardType'] as int? ?? 0
      ..cardNo = json['cardNo'] as String? ?? ''
      ..reply = json['reply'] as int? ?? 0
      ..time0 = time0
      ..time1 = time1
      ..orderTime = time1
      ..energyOrderCode = 'g${a.nzl}ttc${a.fccTTC}v${a.vol}m${a.mny}vs${a.vtot0}sn${SpUtil.getString(Constant.snCode)}'
      ..mdcOrderTime = Utils.timeStamp(time1)
      ..shiftId = CurrentShiftEntity.get()?.id ?? ''
      ..shiftNo = CurrentShiftEntity.get()?.workCycleCode ?? ''

      // 补充数据
      ..goodsPlatformPrice = '${(gunByNzl?.goodsSkuPrice ?? '').toFen}'
      ..mchGoodsId = gunByNzl?.goodsSkuId ?? ''
      ..categoryId = gunByNzl?.categoryId ?? ''
      ..mchGoodsName = gunByNzl?.goodsShortName ?? ''
      ..shelfId = gunByNzl?.shelfId ?? ''
      ..goodsSkuName = gunByNzl?.goodsSkuName ?? ''
      ..unitName = gunByNzl?.unitName ?? ''
      ..exceptionType = (gunByNzl?.getPriceFen() == _prc2 || _prc2 == 0) ? 0 : 1;
  }

  ///手动解析油单
  static void fromJsonHbOrder(AppOrderBean a, dynamic data, int mdcNo) {

    final optTime = (data['time'] is String ? data['time'] : '') as String;
    final time = formatDateTime(optTime);
    final qty = (data['qty'] is int ? data['qty'] : 0) as int;
    final vTot = (data['vTot'] is int ? data['vTot'] : 0) as int;
    a
      ..mdcNo = mdcNo
      ..sta = (data['sta'] is int ? data['sta'] : 0) as int
      ..nzl = (data['nzl'] is int ? data['nzl'] : 0) as int
      ..prc = (data['prc'] is int ? data['prc'] : 0) as int
      ..vol = qty
      ..mny = (data['mny'] is int ? data['mny'] : 0) as int

      ..time0 = time
      ..time1 = time

      ..vtot1 = vTot
      ..vtot0 = vTot - qty
      ..sta = 1

      ..mdcOrderTime = time.isNotEmpty ? DateTime.parse(time).millisecondsSinceEpoch : 0;

    final gunByNzl = UserConfigManager.getGunByNzl(a.nzl);
    a
      ..orderTime = time
      ..energyOrderCode = 'g${a.nzl}v${a.vol}m${a.mny}vs${a.vtot0}sn${SpUtil.getString(Constant.snCode)}'
      ..mdcOrderTime = Utils.timeStamp(time)
      ..shiftId = CurrentShiftEntity.get()?.id ?? ''
      ..shiftNo = CurrentShiftEntity.get()?.workCycleCode ?? ''

    // 补充数据
      ..goodsPlatformPrice = '${(gunByNzl?.goodsSkuPrice ?? '').toFen}'
      ..mchGoodsId = gunByNzl?.goodsSkuId ?? ''
      ..categoryId = gunByNzl?.categoryId ?? ''
      ..mchGoodsName = gunByNzl?.goodsShortName ?? ''
      ..shelfId = gunByNzl?.shelfId ?? ''
      ..goodsSkuName = gunByNzl?.goodsSkuName ?? ''
      ..unitName = gunByNzl?.unitName ?? ''
      ..exceptionType = (gunByNzl?.getPriceFen() == a.prc || a.prc == 0) ? 0 : 1;
  }

  ///转json
  Map<String, dynamic> toUpLoadJson() {
    return {
      'chlNo': chl,
      'deviceSn': SpUtil.getString(Constant.snCode),
      'energyOrderCode': energyOrderCode,
      'energyOrderStartTime': Utils.timeStamp(time0) / 1000,
      'energyOrderTime': Utils.timeStamp(time1) / 1000,
      'exceptionType': exceptionType,

      'goodsPlatformPrice': goodsPlatformPrice,
      'goodsPrice': prc,
      'goodsQuantity': vol,
      'goodsTotalPrice': mny,

      'mchCode': GetUserInfoEntity.get()?.loginMerchantCode,
      'mchGoodsId': mchGoodsId,
      'mchGoodsName': mchGoodsName,
      'mchName': GetUserInfoEntity.get()?.loginMerchantName,

      'mdcNo': mdcNo,
      'mdcTtc': fccTTC,
      'normGoodsCode': gas,

      'pumpAddedValue': vtot1 - vtot0,
      'pumpCodeEnd': vtot1,
      'pumpCodeStart': vtot0,

      'refuelingCardNo': cardNo,
      'refuelingCardType': cardType,

      'refuelingMode': 1, // UserApp.getZeroConfig().refuelingMode 1：无卡模式、 2：外挂、3：卡机联动）

      'shiftNo': shiftNo,
      'shiftId': shiftId,

      'shelfId': shelfId,
      'shelfNo': nzl,
    };
  }

  ///repairOrder
  static AppOrderBean repairOrder(int nzl, int mny) {
    final AppOrderBean order = AppOrderBean();
    final gunByNzl = UserConfigManager.getGunByNzl(nzl);
    final _prc = (gunByNzl?.goodsSkuPrice ?? '').toFen;
    final currentTime = Utils.getCurrentTime();
    final timeStamp = Utils.timeStamp(currentTime);
    order
      ..prc = _prc
      ..nzl = nzl
      ..mny = mny
      // ..vol = (mny / _prc).toFen
      ..vol = '$mny'.divideDefault('$_prc').toFen
      ..time0 = currentTime
      ..time1 = currentTime
      ..orderTime = currentTime
      ..mdcOrderTime = timeStamp
      ..energyOrderCode = 'supply-${nzl}m${timeStamp}sn${SpUtil.getString(Constant.snCode)}'
      ..shiftId = CurrentShiftEntity.get()?.id ?? ''
      ..shiftNo = CurrentShiftEntity.get()?.workCycleCode ?? ''
      ..isSynced = true

      // 补充数据
      ..goodsPlatformPrice = '$_prc'
      ..mchGoodsId = gunByNzl?.goodsSkuId ?? ''
      ..categoryId = gunByNzl?.categoryId ?? ''
      ..mchGoodsName = gunByNzl?.goodsShortName ?? ''
      ..shelfId = gunByNzl?.shelfId ?? ''
      ..goodsSkuName = gunByNzl?.goodsSkuName ?? ''
      ..unitName = gunByNzl?.unitName ?? ''
      ..exceptionType = 0;
    return order;
  }

  ///入库
  static void insertOrder(AppOrderBean order) {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<AppOrderBean>();
    try {
      final query = box.query(AppOrderBean_.energyOrderCode.equals(order.energyOrderCode)).build();
      final results = query.find();
      if (results.isNotEmpty) {
        print('[insertOrder] failed [重复订单] ${order.toStringOrder()}');
        return;
      }
      box.put(order);
      print('[insertOrder] success ${order.toStringOrder()}');
    } catch (e, s) {
      print('[insertOrder] failed ${order.toStringOrder()} [error]: \n$e \n$s');
    }
  }

  ///查询未上传的油单
  static List<AppOrderBean> queryUpLoadOrder() {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<AppOrderBean>();
    // 构建查询构建器
    final queryBuilder = box.query(AppOrderBean_.isSynced.equals(false));
    // 构建查询
    final query = queryBuilder.build()..limit = 30;
    // 执行查询并获取结果
    final results = query.find();
    // 关闭查询以释放资源
    query.close();
    return results;
  }

  /// 查询未支付的油单
  static List<AppOrderBean> queryUnPayOrder() {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<AppOrderBean>();
    // 构建查询构建器
    final queryBuilder = box.query(AppOrderBean_.shiftNo.equals(CurrentShiftEntity.get()?.workCycleCode ?? '') & AppOrderBean_.energyOrderStatus.lessThan(OrderOilStatus.DONE));
    // 构建查询
    final query = queryBuilder.build()..limit = 30;
    // 执行查询并获取结果
    final results = query.find();
    // 关闭查询以释放资源
    query.close();
    return results;
  }

  /// 查询未支付的油单 合并
  static List<AppOrderBean> queryUnPayOrderMerge(List<int> shelfNoList) {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<AppOrderBean>();
    // 构建查询构建器
    final queryBuilder = box.query(
      AppOrderBean_.shiftNo.equals(CurrentShiftEntity.get()?.workCycleCode ?? '') &
          AppOrderBean_.nzl.oneOf(shelfNoList) &
          AppOrderBean_.isSynced.equals(true) &
          AppOrderBean_.energyOrderStatus.lessThan(OrderOilStatus.DONE),
    );
    // 构建查询
    final query = queryBuilder.build()..limit = 30;
    // 执行查询并获取结果
    final results = query.find();
    // 关闭查询以释放资源
    query.close();
    return results;
  }

  /// 通用方法：根据 energyOrderCode 更新指定字段（仅当值变化时更新）
  static void updateFieldsByEnergyOrderCode<T>(
    List<ResUploadOilEntity>? list,
    void Function(AppOrderBean bean, T? value) updateField,
    T? Function(ResUploadOilEntity entity) getValue,
    T? Function(AppOrderBean bean) getCurrentValue,
  ) {
    if (list == null || list.isEmpty) return;

    final store = getIt<ObjectIdBox>().store;
    final box = store.box<AppOrderBean>();

    // 收集所有的 energyOrderCode
    final codes = list.map((e) => e.energyOrderCode).toList();

    // 构建映射关系
    final codeToValueMap = Map.fromEntries(
      list.map((e) => MapEntry(e.energyOrderCode, getValue(e))),
    );

    // 使用 In 查询一次性获取所有需要更新的数据
    final query = box.query(AppOrderBean_.energyOrderCode.oneOf(codes)).build();
    try {
      final results = query.find();
      final List<AppOrderBean> modifiedBeans = []; // 存储有修改的实体

      // 修改查询到的数据
      for (var bean in results) {
        final newValue = codeToValueMap[bean.energyOrderCode];
        final currentValue = getCurrentValue(bean);

        print('search 更新订单状态: ${bean.energyOrderCode} [${currentValue}] -> $newValue');

        // 仅当值不同时才更新
        if (newValue != null && newValue != currentValue) {
          print('update 更新订单状态: ${bean.energyOrderCode} [${currentValue}] -> $newValue');
          updateField(bean, newValue);
          modifiedBeans.add(bean); // 将有修改的实体添加到列表
        }
      }

      // 仅当有修改时才提交更新
      if (modifiedBeans.isNotEmpty) {
        print('real 更新订单状态: ${modifiedBeans.map((e) => e.energyOrderCode).toList()}');
        box.putMany(modifiedBeans);
      }
    } catch (e, s) {
      print('更新失败: $e\n$s');
    } finally {
      query.close();
    }
  }

  /// 批量更新支付状态
  static void updateOrderStatus(List<ResUploadOilEntity>? list) {
    updateFieldsByEnergyOrderCode<int>(
      list,
      (bean, status) {
        print('更新订单状态: ${bean.energyOrderCode} [${bean.energyOrderStatus}] -> $status');
        bean.energyOrderStatus = status!;
      },
      (entity) => entity.energyOrderStatus,
      (bean) => bean.energyOrderStatus,
    );
  }

  /// 批量更新上传状态
  static void updateIsSynced(List<ResUploadOilEntity>? list) {
    updateFieldsByEnergyOrderCode<String>(
      list,
      (bean, id) {
        if (id != null) {
          bean.energyOrderId = id;
          bean.isSynced = true;
        }
      },
      (entity) => entity.energyOrderId,
      (bean) => bean.energyOrderId,
    );
  }

  /// 单笔更新支付状态
  static void updateOrderStatusById(String energyOrderId, int status) {
    if (energyOrderId.isEmpty) {
      print('------>>> [updateOrderStatusById] energyOrderId 不能为空');
      return;
    }
    try {
      final store = getIt<ObjectIdBox>().store;
      final box = store.box<AppOrderBean>();
      final query = box.query(AppOrderBean_.energyOrderId.equals(energyOrderId)).build();
      try {
        final bean = query.findFirst();
        if (bean != null) {
          print('------>>> [updateOrderStatusById] 更新订单状态: ${bean.energyOrderCode} [${bean.energyOrderStatus}] -> $status');
          bean.energyOrderStatus = status;
          box.put(bean);
        } else {
          print('------>>> [updateOrderStatusById] 未找到对应订单: $energyOrderId');
        }
      } finally {
        query.close();
      }
    } catch (e, s) {
      print('------>>> [updateOrderStatusById] 更新失败: $e\n$s');
    }
  }

  /// 单笔更新支付状态byCode energyOrderCode
  static void updateOrderStatusByCode(String energyOrderCode, int status) {
    if (energyOrderCode.isEmpty) {
      print('------>>> [updateOrderStatusByCode] energyOrderCode 不能为空');
      return;
    }
    try {
      final store = getIt<ObjectIdBox>().store;
      final box = store.box<AppOrderBean>();
      final query = box.query(AppOrderBean_.energyOrderCode.equals(energyOrderCode)).build();
      try {
        final bean = query.findFirst();
        if (bean != null) {
          print('------>>> [updateOrderStatusByCode] 更新订单状态: ${bean.energyOrderCode} [${bean.energyOrderStatus}] -> $status');
          bean.energyOrderStatus = status;
          box.put(bean);
        } else {
          print('------>>> [updateOrderStatusByCode] 未找到对应订单: $energyOrderCode');
        }
      } finally {
        query.close();
      }
    } catch (e, s) {
      print('------>>> [updateOrderStatusByCode] 更新失败: $e\n$s');
    }
  }

  /// 批量更新挂起时间
  static void updatePendingTime(List<ResUploadOilEntity>? list) {
    updateFieldsByEnergyOrderCode<String>(
      list,
      (bean, suspendTime) {
        print('更新订单状态：${bean.energyOrderCode} suspendTime:[${bean.suspendTime}] -> $suspendTime');
        bean.suspendTime = suspendTime ?? '';
      },
      (entity) => entity.suspendTime,
      (bean) => bean.suspendTime,
    );
  }

  // 解析时间
  static String formatDateTime(String input) {
    if (input.length != 14 || !RegExp(r'^\d+$').hasMatch(input)) {
      return '';
    }
    return input.replaceRange(4, 4, '-')
        .replaceRange(7, 7, '-')
        .replaceRange(10, 10, ' ')
        .replaceRange(13, 13, ':')
        .replaceRange(16, 16, ':');
  }
}
